<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd()"
          v-hasPermi="['system:category:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" row-key="rid" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'categoryList', hasChildren: 'hasChildren' }">
      <el-table-column label="编号" align="center" prop="rid" width="100" />
      <el-table-column label="分类名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <span v-if="row.status === '2'">启用</span>
          <span v-if="row.status === '1'">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="首页显示" align="center" prop="isHome">
        <template slot-scope="{ row }">
          <span v-if="row.isHome === '2'">显示</span>
          <span v-if="row.isHome === '1'">隐藏</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)"
            v-hasPermi="['system:category:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)"
            v-hasPermi="['system:category:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAdd(row)" v-if="row.parentId === 0"
            v-hasPermi="['system:category:edit']">新增子级</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleFenPei(row)" v-if="row.parentId === 0"
            v-hasPermi="['system:category:edit']">分配热门课程</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left" size="small">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级ID" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级别" style="width: 100%" v-if="!form.rid">
            <el-option label="根目录" :value="0"></el-option>
            <el-option v-for="item in parentList" :key="item.rid" :label="item.name" :value="item.rid"></el-option>
          </el-select>

          <el-select v-model="form.parentId" placeholder="请选择父级别" style="width: 100%" v-else>
            <el-option label="根目录" :value="0"></el-option>
            <el-option v-for="item in parentList.filter(e => e.rid !== form.rid)" :key="item.rid" :label="item.name"
              :value="item.rid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="首页显示" prop="isHome">
          <el-radio-group v-model="form.isHome">
            <el-radio label="2">显示</el-radio>
            <el-radio label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="2">显示</el-radio>
            <el-radio label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="videoTitle" :visible.sync="videoDialog" width="900px" append-to-body :close-on-click-modal="false"
      fullscreen>
      <el-form :model="videoParams" ref="queryForm1" size="small" :inline="true" label-width="68px">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="videoParams.title" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item label="讲师" prop="Lecturer">
          <el-input v-model="videoParams.Lecturer" placeholder="请输入讲师" clearable />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <md-select-tree v-model="videoParams.categoryId" :defaultExpandAll="true" :data="parentList" nodeKey="rid"
            :defaultProps="{ label: 'name', children: 'categoryList' }" placeholder="请选择上级"></md-select-tree>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isNominate">
          <el-select v-model="videoParams.isNominate" placeholder="是否推荐" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否首页" prop="isHome">
          <el-select v-model="videoParams.isHome" placeholder="是否首页" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="videoParams.status" placeholder="状态" clearable>
            <el-option label="显示" value="1"></el-option>
            <el-option label="隐藏" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getListVideo">搜索</el-button>
          <!-- <el-button icon="el-icon-refresh" size="mini" @click="videoResetQuery">重置</el-button> -->
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" ref="multipleTable" :data="videoList" height="60vh" row-key="rid" @select="select">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="left" />
        <el-table-column label="编号" align="left" prop="rid" width="50" />

        <el-table-column label="课程名称" align="left" prop="title" min-width="380" />

        <el-table-column label="讲师" align="left" prop="lecturer" />

        <el-table-column label="创建时间" align="left" prop="createTime" />
      </el-table>

      <pagination v-show="videoTotal > 0" :total="videoTotal" :page.sync="videoParams.pageNum"
        :limit.sync="videoParams.pageSize" @pagination="getListVideo" />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFenPeiForm">分配</el-button>
        <el-button @click="cancelFenPei">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/web/category";
import { listNominateDetail } from "@/api/web/nominateDetails";
import { listVideo } from "@/api/web/video";
export default {
  name: "Category",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 查询参数
      queryParams: {
        name: null,
        status: null,
        isHome: null,
        type: 1
      },
      videoParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null
      },
      videoDialog: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      parentList: [],
      videoTitle: '',
      videoList: [],
      videoTotal: '',
      selectVideos: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {

    select(s, w) {
      console.log(s, w, 'w');
      console.log(this.selectVideos, 'this.selectVideos');
      if (s.length == 0) {
        this.selectVideos = this.selectVideos.filter(item => item !== w.rid)
      } else {
        this.selectVideos = [...new Set(s.map(m => { return m.rid }).concat(this.selectVideos))]
      }
    },
    /** 分配 */
    async handleFenPei(row) {
      this.getParentList();
      this.form = row
      try {
        this.videoTitle = '分配课程'
        if (row.popular) {
          this.selectVideos = row.popular.split(',')
        }
        this.videoDialog = true

        this.getListVideo()
      } catch (error) {
        console.log(error)
      }
    },
    async submitFenPeiForm() {
      try {
        if (this.selectVideos.length === 0) {
          this.$modal.msgWarning("请选择课程");
          return
        }
        console.log(this.form, 'form');
        console.log(this.selectVideos, 'selectVideos最开始');

        const params = Object.assign({}, { ...this.form, popular: this.selectVideos.toString() })
        if (!params.parentId) {
          params.parentId = 0
        }

        updateCategory(params).then(response => {
          if (response.code == 200) {
            this.$modal.msgSuccess("修改成功");
            this.cancelFenPei()
            this.open = false;
            this.getList();
          }

          console.log(response, 'respones');

        });

      } catch (error) {
        console.log(error)
      }
    },
    cancelFenPei() {
      this.selectVideos = []
      this.videoList = []
      this.videoTotal = 0
      this.videoParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null
      }
      this.videoDialog = false
    },
    async getListVideo() {
      this.loading = true
      try {
        const res = await listVideo(this.videoParams)
        this.videoList = res.rows;
        this.videoTotal = res.total;

        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection()
          if (this.selectVideos && this.selectVideos.length > 0) {
            this.selectVideos.forEach((id, index) => {
              const row = this.videoList.find(e => e.rid == id)
              if (row) {
                this.$refs.multipleTable.toggleRowSelection(row, true)
              } else {
                this.$refs.multipleTable.toggleRowSelection(row, false)
              }

              if (index === this.selectVideos.length - 1) {
                this.loading = false
              }
            })
          }
        })
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    /** 查询分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.data;
        this.loading = false;
      });
    },
    /** 查询分类列表 */
    getParentList() {
      listCategory({
        type: 1
      }).then(response => {
        this.parentList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rid: null,
        name: null,
        alias: null,
        parentId: 0,
        remark: null,
        status: '2',
        isHome: '2',
        icon: null,
        type: 1,
        createTime: null,
        updateTime: null,
        deptId: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getParentList();
      this.open = true;
      this.title = "添加分类";
      if (row) {
        this.form.parentId = row.rid
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row,'row');
      this.reset();
      this.getParentList();
      const rid = row.rid || this.ids
      getCategory(rid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const params = Object.assign({}, { ...this.form })
          if (!params.parentId) {
            params.parentId = 0
          }
          if (params.rid != null) {
            updateCategory(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rids = row.rid || this.ids;
      this.$modal.confirm('是否确认删除分类编号为"' + rids + '"的数据项？').then(function () {
        return delCategory(rids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/category/export', {
        ...this.queryParams
      }, `category_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
